package cn.liasoux.config;

import cn.liasoux.common.MsgLog;
import cn.liasoux.mapper.MsgLogMapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.DirectExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
@Slf4j
public class RabbitMQConfig {

    @Autowired
    private CachingConnectionFactory connectionFactory;

    @Value("${spring.rabbitmq.mail.router}")
    private String MAIL_ROUTER_KEY;

    @Value("${spring.rabbitmq.mail.queue}")
    private String MAIL_QUEUE;

    @Value("${spring.rabbitmq.mail.exchange}")
    private String MAIL_EXCHANGE_NAME;

    @Autowired
    MsgLogMapper msgLogMapper;

    @Bean
    public RabbitTemplate rabbitTemplate(){
        RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory);

        rabbitTemplate.setConfirmCallback((correlationData,ack,cause)->{
            if(ack){
                log.info("消息成功发送到Exchange");
                System.out.println("消息成功发送到Exchange");
                String msgId = correlationData.getId();
                //Todo:更新msg_log的发送状态
                MsgLog msgLog = new MsgLog();
                msgLog.setStatus(1);
                msgLogMapper.update(msgLog,new QueryWrapper<MsgLog>().eq("msgId",msgId));
            }else{
                log.info("消息发送Exchange失败,{},cause:{}",correlationData,cause);
            }
            rabbitTemplate.setMandatory(true);
            rabbitTemplate.setReturnCallback((message, replyCode, replyText, exchange, routingKey) -> {
                log.info("消息从Exchange路由到Queue失败: exchange: {}, route: {}, replyCode: {}, replyText: {}, message: {}", exchange, routingKey, replyCode, replyText, message);
            });
        });

        return rabbitTemplate;
    }


    @Bean
    public Queue mailQueue(){
        return new Queue(MAIL_QUEUE,true);
    }

    @Bean
    public DirectExchange mailExchange(){
        return new DirectExchange(MAIL_EXCHANGE_NAME,true,false);
    }

    @Bean
    public Binding mailBinding(){
        return BindingBuilder.bind(mailQueue()).to(mailExchange()).with(MAIL_ROUTER_KEY);
    }
}
